package com.easy.back.config;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CreateCache;
import com.easy.back.interceptors.IpInterceptors;
import com.easy.back.interceptors.OperationInterceptors;
import com.easy.back.service.IOperationService;
import com.easy.back.service.IUserService;
import com.easy.back.utils.JacksonObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Autowired
    private IOperationService operationService;
    @Autowired
    private IUserService userService;

    /**
     * 添加资源处理程序
     *
     * @param registry 注册表
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        log.info("开始进行静态资源映射");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/rent/**").addResourceLocations("classpath:/rent/");
    }

    /**
     * 扩展mvc框架消息转换器
     *
     * @param converters 转换器
     */
    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        log.info("扩展消息转换器");
        //创建消息转换器对象
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        //设置对象转换器，底层使用Jackson将Java对象转换为json
        messageConverter.setObjectMapper(new JacksonObjectMapper());
        //将上面的消息转换器对象追加到mvc框架的转换器集合中
        converters.add(0, messageConverter);
    }

    @CreateCache(area = "suiyizu", name = "login_ip_", expire = 10, timeUnit = TimeUnit.SECONDS)
    private Cache<String, String> ipCache;

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new OperationInterceptors(operationService, userService)).addPathPatterns(
                "/feedback/d",
                "/feedback/u",
                "/house/d",
                "/house/status/**",
                "/house/u",
                "/user/d",
                "/user/u",
                "/user/r",
                "/p/u",
                "/p/d"
        ).order(1);
        registry.addInterceptor(new IpInterceptors(ipCache)).excludePathPatterns(
                "/common/**"
        ).order(0);

    }
}
